package com.yssoft.service.core;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.yssoft.entity.core.*;
import com.yssoft.mapper.core.*;
import com.yssoft.shiro.MyRealm;
import com.yssoft.shiro.MyRealm.ShiroUser;
import com.yssoft.utils.LayuiUtil;
import com.yssoft.utils.SessionUtil;
import com.yssoft.utils.UploadFile;
import com.yssoft.utils.UserHelper;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 陈翼东
 * @time 2018/4/24 下午 02:20
 * @ 人员管理service
 */
@Service
public class PersonService {
    
    @Resource
    private TPersonnelMapper personnelMapper;
    
    @Resource
    private TRolesMapper rolesMapper;
    
    @Resource
    private TAccountsMapper accountsMapper;
    
    @Resource
    private EnterpriseService enterpriseService;
    
    @Resource
    private DepartmentService departmentService;
    
    
    @Resource
    private TPersonnelAttMapper personnelAttMapper;
    
    /**
     * 分页查询人员信息
     *
     * @param pageNumber
     * @param pageSize
     * @param personName
     * @param deptName
     * @param companyName
     * @return
     */
    public JSONObject queryPersonPage(int pageNumber, int pageSize, String personName, String deptName, String companyName) {
        //获取当前登陆账号信息
        Integer entId = UserHelper.getCurrentCompanyId();//企业id
        PageHelper.startPage(pageNumber, pageSize);//下面第一个查询结果进行分页
        Map<String, Object> param = new HashMap<>();
        param.put("companyId", entId);
        param.put("personName", personName);
        param.put("deptName", deptName);
        param.put("companyName", companyName);
        List<Map<String, Object>> personList = personnelMapper.selectAllSql(param);
        int count = personnelMapper.selectCountSql(param);//查询条数
        JSONObject jsonObject = LayuiUtil.getJSONObjectByMap(personList, count, "", "");
        return jsonObject;
    }
    
    /**
     * 删除人员信息
     *
     * @param personId
     */
    @Transactional(rollbackFor = Exception.class)
    public int deletePersonById(String personId) {
        if (personId == null) {
            throw new RuntimeException("人员id不能为null");
        } else if (personId.trim().length() <= 0) {
            throw new RuntimeException("人员id不能为空");
        } else {
        	//查询是否使用
        	Map<String, Object> params=new HashMap<String, Object>();
        	params.put("personId", personId);
        	int count=accountsMapper.queryAccountCount(params);
        	if(count>0) {
        		  throw new RuntimeException("该人员已经被使用，请先删除账户信息，再删除该人员信息");
        	}
        	//没有使用，可以删除
            TPersonnel p = new TPersonnel();
            p.setId(Integer.parseInt(personId));
            TPersonnel person = personnelMapper.selectOne(p);
            person.setDeleteFlag("1");
            return personnelMapper.updateByPrimaryKeySelective(person);
        }
       
    }
    
    /**
     * 根据人员id查询人员
     *
     * @param personId
     * @return
     */
    public TPersonnel queryPersonById(String personId) {
        TPersonnel p = new TPersonnel();
        p.setId(Integer.parseInt(personId));
        return personnelMapper.selectOne(p);
    }
    
    /**
     * 新增人员数据
     *
     * @param person
     * @param idCartFile
     * @param healthCertificateFile
     * @param qualificationCertificateFile
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void addPerson(TPersonnel person, HttpServletRequest request, String[] idCartFile, String[] healthCertificateFile, String[] qualificationCertificateFile) {
        person.setDeleteFlag("0");
        person.setCreateTime(new Date());
        Session session = SecurityUtils.getSubject().getSession();
        TAccounts acc = (TAccounts) session.getAttribute(SessionUtil.USER_SESSION_KEY);
        person.setCreatorId(UserHelper.getCurrentUserId());//创建人
        person.setCreatorName(UserHelper.getCurrentUser().getPersonName());//创建人
        if (acc != null) {
            person.settEId(acc.gettEId());
        }
        TPersonnel personnel = personnelMapper.selectByPrimaryKey(acc.gettPId());
        if (personnel != null) {
            person.setCreatorName(personnel.getName());//创建人姓名
        }
        personnelMapper.insert(person);
        //上传图片
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (idCartFile != null) {
            for (String idCard : idCartFile) {
                TPersonnelAtt personnelAtt = personnelAttMapper.selectByPrimaryKey(Integer.parseInt(idCard));
                String idCardTime = request.getParameter("idCardTime");
                try {
                    if (idCardTime != null && idCardTime.length() > 0) {
                        personnelAtt.setExpiryDate(simpleDateFormat.parse(idCardTime));
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                personnelAtt.settPersonId(person.getId());
                personnelAttMapper.updateByPrimaryKeySelective(personnelAtt);
            }
        }
        if (healthCertificateFile != null) {
            for (String healthCertificate : healthCertificateFile) {
                TPersonnelAtt personnelAtt = personnelAttMapper.selectByPrimaryKey(Integer.parseInt(healthCertificate));
                String healthCertificateTime = request.getParameter("healthCertificateTime");
                try {
                    if (healthCertificateTime != null && healthCertificateTime.length() > 0) {
                        personnelAtt.setExpiryDate(simpleDateFormat.parse(healthCertificateTime));
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                personnelAtt.settPersonId(person.getId());
                personnelAttMapper.updateByPrimaryKeySelective(personnelAtt);
            }
        }
        if (qualificationCertificateFile != null) {
            for (String qualificationCertificate : qualificationCertificateFile) {
                TPersonnelAtt personnelAtt = personnelAttMapper.selectByPrimaryKey(Integer.parseInt(qualificationCertificate));
                String qualificationCertificateTime = request.getParameter("qualificationCertificateTime");
                try {
                    if (qualificationCertificateTime != null && qualificationCertificateTime.length() > 0) {
                        personnelAtt.setExpiryDate(simpleDateFormat.parse(qualificationCertificateTime));
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                personnelAtt.settPersonId(person.getId());
                personnelAttMapper.updateByPrimaryKeySelective(personnelAtt);
            }
        }
        
    }
    
    /**
     * 修改人员数据
     *
     * @param person
     * @param idCartFile
     * @param healthCertificateFile
     * @param qualificationCertificateFile
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int editPerson(TPersonnel person, HttpServletRequest request, String[] idCartFile, String[] healthCertificateFile, String[] qualificationCertificateFile) {
        
        
        if ((person.getId() + "").equals(UserHelper.getCurrentUser().getPersonId() + "")) {
            TAccounts accounts = accountsMapper.selectByPersonId(person.getId());
            MyRealm.ShiroUser shiroUser = new MyRealm.ShiroUser();
            if (accounts != null) {
                shiroUser.setLoginName(accounts.getLoginName());
                if (accounts.gettPId() != null) {
                    shiroUser.setEntId(accounts.gettEId());
                    shiroUser.setId(accounts.getId());
                    shiroUser.setPersonId(accounts.gettPId());
                    if (person != null) {
                        shiroUser.setPersonId(person.getId());
                        shiroUser.setPersonName(person.getName());
                        TDepartment dept = departmentService.queryTDepartmentById(person.gettDId());
                        if (dept != null) {
                            shiroUser.setDeptId(dept.getId());
                            shiroUser.setDeptName(dept.getName());
                        }
                    }
                }
                TEnterprise ent = enterpriseService.queryEnterpriseById(accounts.gettEId());
                if (ent != null) {
                    shiroUser.setEntName(ent.getName());
                }
            }
            request.getSession().setAttribute(SessionUtil.USER_SESSION, shiroUser);
        }
        
        String[] qualificationIds = request.getParameterValues("qualificationId");
        String[] healthIds = request.getParameterValues("healthId");
        String[] idCardIds = request.getParameterValues("idCardId");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //修改原来的图片的日期
        if (idCardIds != null) {
            for (String idCardId : idCardIds) {
                TPersonnelAtt personAtt = personnelAttMapper.selectByPrimaryKey(Integer.parseInt(idCardId));
                String idCardTime = request.getParameter("idCardTime");
                try {
                    if (idCardTime != null && idCardTime.length() > 0) {
                        personAtt.setExpiryDate(simpleDateFormat.parse(idCardTime));
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                personnelAttMapper.updateByPrimaryKeySelective(personAtt);
            }
        }
        if (healthIds != null) {
            for (String healthId : healthIds) {
                TPersonnelAtt personAtt = personnelAttMapper.selectByPrimaryKey(Integer.parseInt(healthId));
                String healthCertificateTime = request.getParameter("healthCertificateTime");
                try {
                    if (healthCertificateTime != null && healthCertificateTime.length() > 0) {
                        personAtt.setExpiryDate(simpleDateFormat.parse(healthCertificateTime));
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                personnelAttMapper.updateByPrimaryKeySelective(personAtt);
            }
        }
        if (qualificationIds != null) {
            for (String qualificationId : qualificationIds) {
                TPersonnelAtt personAtt = personnelAttMapper.selectByPrimaryKey(Integer.parseInt(qualificationId));
                String qualificationCertificateTime = request.getParameter("qualificationCertificateTime");
                try {
                    if (qualificationCertificateTime != null && qualificationCertificateTime.length() > 0) {
                        personAtt.setExpiryDate(simpleDateFormat.parse(qualificationCertificateTime));
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                personnelAttMapper.updateByPrimaryKeySelective(personAtt);
            }
        }
        //保存信息图片
        if (idCartFile != null) {
            for (String idCard : idCartFile) {
                TPersonnelAtt personnelAtt = personnelAttMapper.selectByPrimaryKey(Integer.parseInt(idCard));
                String idCardTime = request.getParameter("idCardTime");
                try {
                    if (idCardTime != null && idCardTime.length() > 0) {
                        personnelAtt.setExpiryDate(simpleDateFormat.parse(idCardTime));
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                personnelAtt.settPersonId(person.getId());
                personnelAttMapper.updateByPrimaryKeySelective(personnelAtt);
            }
        }
        if (healthCertificateFile != null) {
            for (String healthCertificate : healthCertificateFile) {
                TPersonnelAtt personnelAtt = personnelAttMapper.selectByPrimaryKey(Integer.parseInt(healthCertificate));
                String healthCertificateTime = request.getParameter("healthCertificateTime");
                try {
                    if (healthCertificateTime != null && healthCertificateTime.length() > 0) {
                        personnelAtt.setExpiryDate(simpleDateFormat.parse(healthCertificateTime));
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                personnelAtt.settPersonId(person.getId());
                personnelAttMapper.updateByPrimaryKeySelective(personnelAtt);
            }
        }
        if (qualificationCertificateFile != null) {
            for (String qualificationCertificate : qualificationCertificateFile) {
                TPersonnelAtt personnelAtt = personnelAttMapper.selectByPrimaryKey(Integer.parseInt(qualificationCertificate));
                String qualificationCertificateTime = request.getParameter("qualificationCertificateTime");
                try {
                    if (qualificationCertificateTime != null && qualificationCertificateTime.length() > 0) {
                        personnelAtt.setExpiryDate(simpleDateFormat.parse(qualificationCertificateTime));
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                personnelAtt.settPersonId(person.getId());
                personnelAttMapper.updateByPrimaryKeySelective(personnelAtt);
            }
        }
        
        return personnelMapper.updateByPrimaryKeySelective(person);
    }
    
    /**
     * 使用手机号查询人员
     *
     * @param phone
     * @return
     */
    public TPersonnel queryPersonByPhone(String phone) {
        return personnelMapper.selectByPhone(phone);
    }
    
    /**
     * 修改手机号
     *
     * @param person
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(TPersonnel person) {
    	String phoneNumber=person.getPhone();
    	person=  queryPersonById(person.getId()+"");
		person.setPhone(phoneNumber);
    	//更新登录账号
		TAccounts acc = accountsMapper.selectByPersonId(  person.getId() );
		acc.setLoginName( phoneNumber);
		accountsMapper.updateByPrimaryKeySelective(acc);
        personnelMapper.updateByPrimaryKeySelective(person);
        
    }
    
    /**
     * 获取人员证照预警数据
     * 王永宁
     *
     * @param page
     * @param limit
     * @param name 
     * @return
     */
    public JSONObject queryWarningPersonPage(int page, int limit, String companyId, String card, String health, String test, String name) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); //制定日期格式
        Calendar c = Calendar.getInstance();
        Date date = new Date();
        c.setTime(date);
        String validityDate = df.format(c.getTime());
        PageHelper.startPage(page, limit);//下面第一个查询结果进行分页
        Map<String, Object> param = new HashMap<>();
        param.put("name", name);
        if (card != null && card != "") {
            switch (card) {
                case "1":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 1);
                    validityDate = df.format(c.getTime());
                    param.put("card", validityDate);
                    break;
                case "2":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 2);
                    validityDate = df.format(c.getTime());
                    param.put("card", validityDate);
                    break;
                case "3":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 3);
                    validityDate = df.format(c.getTime());
                    param.put("card", validityDate);
                    break;
                case "4":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 4);
                    validityDate = df.format(c.getTime());
                    param.put("card", validityDate);
                    break;
                case "5":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 5);
                    validityDate = df.format(c.getTime());
                    param.put("card", validityDate);
                    break;
                case "6":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 6);
                    validityDate = df.format(c.getTime());
                    param.put("card", validityDate);
                    break;
                case "0":
                    param.put("nocard", "0");
                    break;
            }
        }
        if (health != null && health != "") {
            switch (health) {
                case "1":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 1);
                    validityDate = df.format(c.getTime());
                    param.put("health", validityDate);
                    break;
                case "2":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 2);
                    validityDate = df.format(c.getTime());
                    param.put("health", validityDate);
                    break;
                case "3":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 3);
                    validityDate = df.format(c.getTime());
                    param.put("health", validityDate);
                    break;
                case "4":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 4);
                    validityDate = df.format(c.getTime());
                    param.put("health", validityDate);
                    break;
                case "5":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 5);
                    validityDate = df.format(c.getTime());
                    param.put("health", validityDate);
                    break;
                case "6":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 6);
                    validityDate = df.format(c.getTime());
                    param.put("health", validityDate);
                    break;
                case "0":
                    param.put("nohealth", "0");
                    break;
            }
        }
        if (test != null && test != "") {
            switch (test) {
                case "1":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 1);
                    validityDate = df.format(c.getTime());
                    param.put("test", validityDate);
                    break;
                case "2":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 2);
                    validityDate = df.format(c.getTime());
                    param.put("test", validityDate);
                    break;
                case "3":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 3);
                    validityDate = df.format(c.getTime());
                    param.put("test", validityDate);
                    break;
                case "4":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 4);
                    validityDate = df.format(c.getTime());
                    param.put("test", validityDate);
                    break;
                case "5":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 5);
                    validityDate = df.format(c.getTime());
                    param.put("test", validityDate);
                    break;
                case "6":
                    c.setTime(date);
                    c.add(Calendar.MONTH, 6);
                    validityDate = df.format(c.getTime());
                    param.put("test", validityDate);
                    break;
                case "0":
                    param.put("notest", "0");
                    break;
            }
        }
        if (companyId != null && companyId != "") {
            String[] ids = companyId.split(",");
            param.put("companyId", ids);
        }
        List<Map<String, Object>> list = personnelMapper.selectAllSqlForWarning(param);
        int count = personnelMapper.selectCountSqlForWarning(param);//查询条数
        JSONObject jsonObject = LayuiUtil.getJSONObjectByMap(list, count, "", "");
        return jsonObject;
    }
    
    /**
     * 查询当前人员的图片信息
     *
     * @param person
     * @return
     */
    public List<TPersonnelAtt> queryPersonIdCardImg(TPersonnel person) {
        Map<String, Object> params = new HashMap();
        params.put("personId", person.getId());
        params.put("type", "1");
        return personnelAttMapper.selectByPerson(params);
    }
    
    /**
     * 查询当前人员的图片信息
     *
     * @param person
     * @return
     */
    public List<TPersonnelAtt> queryPersonQualificationImg(TPersonnel person) {
        Map<String, Object> params = new HashMap();
        params.put("personId", person.getId());
        params.put("type", "3");
        return personnelAttMapper.selectByPerson(params);
    }
    
    /**
     * 查询当前人员的图片信息
     *
     * @param person
     * @return
     */
    public List<TPersonnelAtt> queryPersonHealthImg(TPersonnel person) {
        Map<String, Object> params = new HashMap();
        params.put("personId", person.getId());
        params.put("type", "2");
        return personnelAttMapper.selectByPerson(params);
    }
    
    public void deleteImg(String imgId) {
        TPersonnelAtt img = personnelAttMapper.selectByPrimaryKey(Integer.parseInt(imgId));
        img.setDeleteFlag("1");
        personnelAttMapper.updateByPrimaryKeySelective(img);
    }
    
    /**
     * 上传图片
     *
     * @param file
     * @param type
     * @return
     */
    public TPersonnelAtt uploadImg(MultipartFile file, String type) {
        //新增图片的时候
        TPersonnelAtt personnelAtt = new TPersonnelAtt();
        Map<String, Object> urlMap = UploadFile.compressUploadedFile(file);
        personnelAtt.setUrl(urlMap.get("fileName") + "");
        personnelAtt.setTurl(urlMap.get("thumbnails") + "");
        personnelAtt.setDeleteFlag("0");
        personnelAtt.setType(type);
        personnelAtt.setCreateTime(new Date());
        personnelAtt.setCreatorId(UserHelper.getCurrentUserId());
        personnelAtt.setCreatorName(UserHelper.getCurrentUser().getPersonName());
        personnelAttMapper.insert(personnelAtt);
        return personnelAtt;
    }
	/**
	 * 获取人员证照预警数据-new
	 * 王永宁
	 * @param page
	 * @param limit
	 * @return
	 */
	public JSONObject queryWarningPersonPageNew(int page, int limit,String companyId, String card, String type) {
		SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd"); //制定日期格式
		Calendar c=Calendar.getInstance();
		Date date=new Date();
		c.setTime(date);
		String validityDate=df.format(c.getTime());  
		PageHelper.startPage(page,limit);//下面第一个查询结果进行分页
		Map<String,Object> param=new HashMap<>();
		if(card!=null&&card!=""){
			switch (card) {
			case "1":
				c.setTime(date);
				c.add(Calendar.MONTH,1); 
				validityDate=df.format(c.getTime());  
				param.put("card",validityDate);
				break;
			case "2":
				c.setTime(date);
				c.add(Calendar.MONTH,2); 
				validityDate=df.format(c.getTime());  
				param.put("card",validityDate);
				break;
			case "3":
				c.setTime(date);
				c.add(Calendar.MONTH,3); 
				validityDate=df.format(c.getTime());  
				param.put("card",validityDate);
				break;
			case "4":
				c.setTime(date);
				c.add(Calendar.MONTH,4); 
				validityDate=df.format(c.getTime());  
				param.put("card",validityDate);
				break;
			case "5":
				c.setTime(date);
				c.add(Calendar.MONTH,5); 
				validityDate=df.format(c.getTime());  
				param.put("card",validityDate);
				break;
			case "6":
				c.setTime(date);
				c.add(Calendar.MONTH,6); 
				validityDate=df.format(c.getTime());  
				param.put("card",validityDate);
				break;
			case "0":
				param.put("nocard","0");
				break;
			}
		}
		
		if(companyId!=null&&companyId!=""){
			String[] ids = companyId.split(",");
			param.put("companyId",ids);
		}
		if(type==null){
			param.put("type","1");
		}else{
			param.put("type",type);
		}
		List<Map<String,Object>> list = personnelMapper.selectAllSqlForWarningNew(param);
		for (Map<String, Object> map : list) {
			if(map.get("cDate")!=null&&map.get("cDate")!=""){
				int res=map.get("cDate").toString().compareTo(df.format(new Date()));
				if(res>=0){
					map.put("guoqi", "0");
				}else{
					map.put("guoqi", "1");
				}
				
			}
			 String phone = map.get("phone").toString();
			 map.put("phone", phone.substring(0,3)+"****"+phone.substring(7,11));
			Map<String, Object> params = new HashMap();
	        params.put("personId", map.get("id"));
	        if(type==null){
				params.put("type","1");
			}else{
				params.put("type",type);
			}
	        List<TPersonnelAtt> picList = personnelAttMapper.selectByPerson(params);
	        
	        if(picList!=null){
	        	map.put("picList", picList);
	        }else{
	        	map.put("picList", "");
	        	
	        }
		}
		int count = personnelMapper.selectCountSqlForWarningNew(param);//查询条数
		JSONObject jsonObject = LayuiUtil.getJSONObjectByMap(list,count,"","");
		return jsonObject;
	}
	
	/**
	 * @方法名称: queryPersonByRecord
	 * @功能描述: 获取人员信息
	 * @作者: 洪丰
	 * @创建时间:2018年6月26日 下午2:15:40
	 * @param record
	 * @return int
	 */
	public int queryPersonByRecord(TPersonnel record){
		List<TPersonnel> personList = personnelMapper.select(record);
		return personList.size();
	}
}
